//
//  HDCFLoginVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/3.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFLoginVc.h"
#import "HDCFRegisterVc.h"
#import "SVProgressHUD.h"
#import "HttpRequest.h"
#import "HDCFFindPsw.h"
#define KFundList @"api/Auth/Login"
#import <CommonCrypto/CommonDigest.h>

@interface HDCFLoginVc ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@end

@implementation HDCFLoginVc

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer*tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(registFirstRespond:)];
    [self.view addGestureRecognizer:tap];
    self.passwordTF.returnKeyType=UIReturnKeyDone;
    self.passwordTF.delegate=self;
    [self.navigationItem setTitle:@"登录"];
   
}

-(void)registFirstRespond:(UIGestureRecognizer*)tap
{
    [self.view endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)loginClick:(UIButton *)sender {
    if (self.phoneTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (self.phoneTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    
    [SVProgressHUD show];
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"md5Pw"] = self.passwordTF.text;
//    paramets[@"Token"] = @"";
//    paramets[@"TimeStamp"] = @"";
//    paramets[@"Name"] = @"";
//    paramets[@"LoginName"] = self.phoneTF.text;
//    paramets[@"Pwd"] = self.passwordTF.text;
    paramets[@"Phone"] = self.phoneTF.text;
    paramets[@"deviceName"] = @"ios";
//    paramets[@"Id"] = @"";
    NSString *jsonStr = [self dictionaryToJson:paramets];
    [HttpRequest sendSelfPostRequestWithURL:KFundList WithParamets:jsonStr WithParamet:nil success:^(id result) {
        
        NSDictionary*resultDic=(NSDictionary*)result;
        NSNumber *code=[resultDic objectForKey:@"code"];
        if ([code integerValue]==1) {
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            [SVProgressHUD dismissWithDelay:1.0];
            NSDictionary *dataDict = result[@"result"];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            if (dataDict[@"Token"]) {
                [user setValue:dataDict[@"Token"] forKey:@"Token"];
            }
            NSLog(@"%@",dataDict[@"LoginName"]);
            if (dataDict[@"LoginName"]&&![dataDict[@"LoginName"] isEqual:[NSNull null]]&&![dataDict[@"LoginName"] isEqualToString:@"<null>"]) {
                [user setValue:dataDict[@"LoginName"] forKey:@"accountName"];
                [user setValue:dataDict[@"Id"] forKey:@"userId"];
            }
            NSNumber *openStatus = dataDict[@"HoldingCode"];
            if (openStatus &&![openStatus isEqual:[NSNull null]]) {
                [user setValue:openStatus.stringValue forKey:@"OpenStatue"];

            }
            
            NSString *exToken = [NSString stringWithFormat:@"%@%@", self.passwordTF.text, dataDict[@"Token"]];
            NSString *md5Str = [self md5:exToken];
            [user setValue:md5Str forKey:@"exToken"];
            
            [user synchronize];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
            if ([self.delegate respondsToSelector:@selector(loginSucess)]) {
                [self.delegate loginSucess];
            }

        }else
        {
            [SVProgressHUD showInfoWithStatus:[resultDic objectForKey:@"msg"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
- (IBAction)forgetPassWord:(UIButton *)sender {
    HDCFFindPsw *vc = [[HDCFFindPsw alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (IBAction)registerClick:(UIButton *)sender {
    HDCFRegisterVc *vc = [[HDCFRegisterVc alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}


@end
